package com.cwf.metadatamanage.config;

import org.neo4j.ogm.session.SessionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.transaction.Neo4jTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Objects;

@Configuration
@EnableNeo4jRepositories(basePackages = "com.grgbanking.metadata.repository")
@EnableTransactionManagement
public class Neo4jConfig {

    @Value("${spring.data.neo4j.uri}")
    private String uri;

    @Value("${spring.data.neo4j.username}")
    private String userName;

    @Value("${spring.data.neo4j.password}")
    private String password;

    @Value("${spring.data.neo4j.uris}")
    private String[] uris;

    @Bean
    public org.neo4j.ogm.config.Configuration getConfiguration() {
        org.neo4j.ogm.config.Configuration configuration = null;

        if (Objects.nonNull(uris) && uris.length > 0) {
            // 集群配置
            configuration = new org.neo4j.ogm.config.Configuration.Builder()
                    .uris(uris)
                    .connectionPoolSize(100)
                    .credentials(userName, password)
                    .withBasePackages("com.cwf.metadatamanage")
                    .build();
        } else {
            // 单机配置
            configuration = new org.neo4j.ogm.config.Configuration.Builder()
                    .uri(uri)
                    .connectionPoolSize(100)
                    .credentials(userName, password)
                    .withBasePackages("com.cwf.metadatamanage")
                    .build();
        }
        return configuration;
    }

    @Bean
    public SessionFactory sessionFactory() {
        return new SessionFactory(getConfiguration());
    }


    @Bean("neo4jTransaction")
    public Neo4jTransactionManager neo4jTransactionManager(SessionFactory sessionFactory) {
        return new Neo4jTransactionManager(sessionFactory);
    }
}